package com.example.demo.util;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URI;
/**
 * 带参数的GET请求
 * 两种方式：
 *       1.直接将参数拼接到url后面 如：?wd=java
 *       2.使用URI的方法设置参数 setParameter("wd", "java")
 */
public class UrlCheck {
    public static void main(String[] args) throws Exception {

        ((LoggerContext) LoggerFactory.getILoggerFactory())
                .getLoggerList()
                .forEach(logger -> logger.setLevel(Level.ERROR));

        File file = new File("D:\\output\\lmedic_live_replay_unsuccess_1.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        // 定义请求的参数
//        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();

        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = null;
        try {
            FileInputStream inputStream = new FileInputStream("D:\\input\\medic_live_replay_success.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            if(!file.exists()) {
                file.createNewFile();
            }

            fw = new FileWriter( file.getAbsoluteFile(), true);  //true续写新内容
            bw = new BufferedWriter(fw);

            String str = null;
            int i = 0;
            while ((str = bufferedReader.readLine()) != null) {
                // 创建Httpclient对象
                i++;
                httpclient = HttpClientBuilder.create().build();
                System.out.println("正在处理完成："+str+"   个数："+i);
                URI uri = new URIBuilder(str).build();
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(uri);
                //response 对象
                // 执行http get请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为404
                if (response.getStatusLine().getStatusCode() == 404) {
                    System.out.println(str);
                    bw.write(str+"\r\n");
                    bw.flush();
                }
                System.out.println("处理完成："+str+"   个数："+i);

            }

            //close
            bw.close();
            inputStream.close();
            bufferedReader.close();

        } finally {
            if (response != null) {
                response.close();
            }
            if(httpclient != null){
                httpclient.close();
            }
        }
    }
}



